package org.security.handler.filter;

import org.pmw.tinylog.Logger;
import org.security.config.FreeProperties;
import org.security.config.web.AbstractFreeSecurityWebConfig;
import org.security.config.web.UrlPermissionConfig;
import org.security.enums.CustomExceptionType;
import org.security.exception.CustomException;
import org.security.handler.BeforeFilterHandler;
import org.security.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author jt
 * 授权
 * @version 1.0
 * @date 2024/6/25 16:41
 */
@Component
public class AuthorizationHandler implements BeforeFilterHandler {

    @Autowired
    private FreeProperties properties;

    @Autowired
    private AbstractFreeSecurityWebConfig config;

    @Override
    public Integer getIndex() {
        return 10;
    }

    @Override
    public String getName() {
        return "AuthorizationHandler";
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(properties.getTokenKey());
        if(token!=null){
            JwtUtil.JwtPayloadInfo payloadInfo = JwtUtil.verify(token);
            // TODO: 2024/7/28 判断当前接口是否有权限
            List<UrlPermissionConfig.UrlPermission> urlPermissionList =
                    config.urlPermissionConfig.getUrlPermissionList()
                    .stream()
                    .filter(res -> request.getRequestURI().equals(res.getUrl())).collect(Collectors.toList());

            if(urlPermissionList.size()>0){
                //token中包括该权限
                if(payloadInfo.getScopes().contains(urlPermissionList.get(0).getPermission())){
                    Logger.info("授权成功");
                }
                else {
                    CustomException.errorToResponse(response,HttpStatus.UNAUTHORIZED, CustomExceptionType.UNAUTHORIZED);
                }
            }

            Logger.info(payloadInfo);

        }else {
            CustomException.errorToResponse(response, HttpStatus.UNAUTHORIZED, CustomExceptionType.TOKEN_ERROR);
        }

    }
}
